package com.syedu.day15;

/**
 * description：Volatile关键字屏蔽JVM指令重排的案例
 * @author Administrator
 * @date 2022/4/2 14:17
 */
public class VolatileDemo {
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 500000; i++) {
            State state = new State();
            ThreadA threadA = new ThreadA(state);
            ThreadB threadB = new ThreadB(state);
            threadA.start();
            threadB.start();
            threadA.join();
            threadB.join();
        }
    }

    static class ThreadA extends Thread {
        private final VolatileDemo.State state;

        public ThreadA(VolatileDemo.State state) {
            this.state = state;
        }

        @Override
        public void run() {
            state.a = 1;
            state.b = 1;
            state.c = 1;
            state.d = 1;
        }
    }

    static class ThreadB extends Thread {
        private final VolatileDemo.State state;

        public ThreadB(VolatileDemo.State state) {
            this.state = state;
        }

        @Override
        public void run() {
            if (state.b == 1 && state.a == 0) {
                System.out.println("b == 1");
            }
            if (state.c == 1 && (state.b == 0 || state.a == 0)) {
                System.out.println("c == 1");
            }
            if (state.d == 1 && (state.a == 0 || state.b == 0)) {
                System.out.println("d == 1");
            }
        }
    }

    static class State {
        // volatile屏蔽JVM指令重排
        public volatile int a = 0;
        public volatile int b = 0;
        public volatile int c = 0;
        public volatile int d = 0;
    }
}